/* eslint-disable react/prop-types */
import {
  BrowserRouter,
  HashRouter,
  Routes,
  Route,
  Navigate
} from 'react-router-dom'
import React, { Suspense } from 'react'
import routerConfig from './router.config'
// 路由拦截
const BeforeRoutes = ({ item }) => {
  document.title = item.meta?.title || '八维创作平台'
  return item.to ? <Navigate to={item.to} /> : <item.element />
}

// 路由渲染
const renderRoutes = (routes) => {
  // routes 路由表数据
  return routes.map((item) => {
    return (
      <Route
        path={item.path}
        key={item.path}
        element={<BeforeRoutes item={item} />}
      >
        {item.children && renderRoutes(item.children)}
      </Route>
    )
  })
}

const RouterView = () => {
  const { mode = 'history', routes } = routerConfig
  return mode === 'history'
    ? (
    <BrowserRouter>
      <Suspense loading={<>loading...</>}>
        <Routes>{renderRoutes(routes)}</Routes>
      </Suspense>
    </BrowserRouter>
      )
    : (
    <HashRouter>
      <Suspense loading={<>loading...</>}>
        <Routes>{renderRoutes(routes)}</Routes>
      </Suspense>
    </HashRouter>
      )
}

export default RouterView
